﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using ComLib.ComFun;
using System.IO;
using ComLib.ConfigService;
using LogLib;
using System.Windows.Forms;

namespace ProcessConfig
{
    public class ConfigService
    {
        #region Static Fields
        protected static List<string> _messages = new List<string>();
        public static string ErrorMessage
        {
            get
            {
                StringBuilder build = new StringBuilder();
                for (int i = 0; i < _messages.Count; i++)
                {
                    build.Append(_messages[i]);
                    build.Append("; ");
                }
                return build.ToString();
            }
        }

        public static void AddErrorMessage(string s)
        {
            _messages.Add(s);
        }

        public static IConfig GetConfig(Type t)
        {
            CreateInstance();
            return _instance[t];
        }

        #endregion

        #region Singleton
        private static ConfigService _instance;
        private static readonly object lockRoot = new object();
        private ConfigService()
        {
            CreatConfigObjects();
        }

        public static void CreateInstance()
        {
            if (_instance == null)
            {
                lock (lockRoot)
                {
                    if (_instance == null)
                    {
                        _instance = new ConfigService();
                    }
                }
            }
        }

        public static ConfigService GetInstance()
        {
            CreateInstance();
            return _instance;
        }

        #endregion

        /// <summary>
        /// 所有的配置类型参数CreatConfigObjects
        /// </summary>
        private Dictionary<Type, IConfig> DicConfig = new Dictionary<Type, IConfig>();

        private void CreatConfigObjects()
        {
            try
            {
                Assembly asm = Assembly.GetExecutingAssembly();
                foreach (Type t in asm.GetTypes())
                {
                    if (t.BaseType.Equals(typeof(IniConfigBase))
                        || t.BaseType.Equals(typeof(SerializeBase))
                        || t.BaseType.Equals(typeof(XmlSerializeBase)))
                    {
                        IConfig cfg = (IConfig)asm.CreateInstance(t.FullName);
                        DicConfig.Add(t, cfg);
                    }
                }               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Log.WriteException(ex.ToString());
            }
          
        }

        public IConfig this[Type t]
        {
            get
            {
                if (DicConfig.ContainsKey(t))
                {
                    return DicConfig[t];
                }
                else
                {
                    return null;
                }
            }
            set
            {
                if (!DicConfig.ContainsKey(t))
                {
                    DicConfig.Add(t, value);
                }
                else
                {
                    DicConfig[t] = value;
                }
            }
        }

        /// <summary>
        /// 不存在的配置文件列表
        /// </summary>
        private List<string> _listNotFindConfigFiles = new List<string>();

        /// <summary>
        /// 加载错误的配置文件列表
        /// </summary>
        private List<string> _listLoadFailedConfigFiles = new List<string>();

        /// <summary>
        /// 保存错误的配置文件列表
        /// </summary>
        private List<string> _listSaveFailedConfigFiles = new List<string>();

        public void LoadConfig()
        {
            IConfig[] cfgs = DicConfig.Values.ToArray<IConfig>();
            for (int i = 0; i < cfgs.Length; i++)
            {
                IConfig cfg = cfgs[i];
                if (!File.Exists(cfg.ConfigFilePath))
                {
                    _listNotFindConfigFiles.Add(cfg.ConfigFilePath + "不存在! 已添加默认配置.");
                    cfg.Save();
                    continue;
                }
                if (!cfg.Load())
                {
                    _listLoadFailedConfigFiles.Add(cfg.ErrorMessage);
                }
            }
        }

        public void SaveConfig()
        {
            IConfig[] cfgs = DicConfig.Values.ToArray<IConfig>();
            foreach (IConfig cfg in cfgs)
            {
                if (!cfg.Save())
                {
                    _listSaveFailedConfigFiles.Add(cfg.ErrorMessage);
                }
            }
        }


        /// <summary>
        /// 检查所有参数是否正常加载
        /// </summary>
        /// <returns></returns>
        public bool CheckLoadAllSuccess()
        {
            return _listLoadFailedConfigFiles.Count == 0
                && _listNotFindConfigFiles.Count == 0;
        }

        /// <summary>
        /// 检查所有参数是否正常保存
        /// </summary>
        /// <returns></returns>
        public bool CheckSaveAllSuccess()
        {
            return _listSaveFailedConfigFiles.Count == 0;
        }

        public string[] GetLoadErrors()
        {
            string[] arr0 = _listNotFindConfigFiles.ToArray();
            string[] arr1 = _listLoadFailedConfigFiles.ToArray();
            return arr0.Union(arr1).ToArray();
        }

        public string[] GetSaveErrors()
        {
            string[] arr0 = _listSaveFailedConfigFiles.ToArray();
            return arr0;
        }

        public List<string> GetAllConfigValues()
        {
            List<string> listStrings = new List<string>();
            foreach (IConfig cfg in DicConfig.Values)
            {
                listStrings.Add(cfg.ToString());
            }
            return listStrings;
        }
    }
}
